package bluejack.operation;
import nme.errors.Error;
import nme.events.Event;
import nme.events.IOErrorEvent;
import nme.events.ProgressEvent;
import nme.Lib;
import nme.net.URLLoader;
import nme.net.URLLoaderDataFormat;
import nme.net.URLRequest;

/**
 * ...
 * @author BlueJack
 */

class URLLoadOper extends Oper
{
	public var url:String;
	public var dataFormat:URLLoaderDataFormat;
	public var handler:Dynamic->Void;
	public var data:Dynamic;
	
	public function new(url:String=null) {
		this.url = url;
		super();
	}
	
	override public function execute():Void {
		var loader:URLLoader = new URLLoader();
		loader.dataFormat = dataFormat;
		loader.addEventListener(Event.COMPLETE, result);
		loader.addEventListener(IOErrorEvent.IO_ERROR, fault);
		loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
		try {
			loader.load(new URLRequest(url));
		}catch (err:Error) {
			trace("Error loading requested document: " + url);
		}
		super.execute();
	}
	
	private function progressHandler(event:ProgressEvent):Void {
			dispatchEvent(event);
	}
	
	override public function result(event:Dynamic = null):Void {
		data = event.target.data;
		if (handler != null) handler(data);
		super.result(event);
	}
}